package com.dy.dws.UserRegisterWin;

import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson.JSONObject;
import com.dy.realtime.common.base.BaseApp;
import com.dy.realtime.common.bean.DwsUserRegisterBean;
import com.dy.realtime.common.constant.Constant;
import com.dy.realtime.common.util.DateFormatUtil;
import com.dy.realtime.common.util.DorisMapFunction;
import com.dy.realtime.common.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.ArrayList;

/**
 * @projectName: MedicalTreatment
 * @package: com.dy.dws.UserRegisterWin
 * @className: DwsUserRegisterWin
 * @author: DuanYu
 * @description: TODO
 * @date: 2025/3/16 15:57
 * @version: 1.0
 * 用户域用户注册各窗口汇总表
 */

public class DwsUserRegisterWin extends BaseApp {
    public static void main(String[] args) {
        new DwsUserRegisterWin().start(Constant.TOPIC_DWD_TRADE_USER_REGISTER, Constant.TOPIC_DWS_TRADE_USER_REGISTER_WIN, 4, 10025);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> dataStreamSource) {
        SingleOutputStreamOperator<JSONObject> etlStream = getEtlStream(dataStreamSource);
//        etlStream.print();
        SingleOutputStreamOperator<DwsUserRegisterBean> mapStream = getMapStream(etlStream);
//        mapStream.print();
        SingleOutputStreamOperator<DwsUserRegisterBean> result = getProcess(mapStream);
        result.map(new DorisMapFunction<>()).sinkTo(FlinkSinkUtil.getDorisSink("dws_user_patient_add_win"));


    }

    private static SingleOutputStreamOperator<DwsUserRegisterBean> getProcess(SingleOutputStreamOperator<DwsUserRegisterBean> mapStream) {
        return mapStream.assignTimestampsAndWatermarks(WatermarkStrategy.<DwsUserRegisterBean>forBoundedOutOfOrderness(Duration.ofSeconds(5)).withTimestampAssigner(new SerializableTimestampAssigner<DwsUserRegisterBean>() {
                    @Override
                    public long extractTimestamp(DwsUserRegisterBean dwsUserRegisterBean, long l) {
                        return dwsUserRegisterBean.getTs();
                    }
                }))
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .process(new ProcessAllWindowFunction<DwsUserRegisterBean, DwsUserRegisterBean, TimeWindow>() {
                    @Override
                    public void process(ProcessAllWindowFunction<DwsUserRegisterBean, DwsUserRegisterBean, TimeWindow>.Context context, Iterable<DwsUserRegisterBean> iterable, Collector<DwsUserRegisterBean> collector) throws Exception {
                        ArrayList<DwsUserRegisterBean> dwsUserRegisterBeans = ListUtil.toList(iterable);
                        long count = dwsUserRegisterBeans.stream().map(e -> e.getCreateTime()).count();
                        String start = DateFormatUtil.tsToDateTime(context.window().getStart());
                        String end = DateFormatUtil.tsToDateTime(context.window().getEnd());
                        String curDate = DateFormatUtil.tsToDate(System.currentTimeMillis());
                        DwsUserRegisterBean next = dwsUserRegisterBeans.iterator().next();
                        collector.collect(DwsUserRegisterBean.builder()
                                .id(next.getId())
                                .createTime(next.getCreateTime())
                                .email(next.getEmail())
                                .telephone(next.getTelephone())
                                .username(next.getUsername())
                                .stt(start)
                                .edt(end)
                                .register_user_count(count)
                                .curDate(curDate)

                                .build());
                    }
                });
    }

    private static SingleOutputStreamOperator<DwsUserRegisterBean> getMapStream(SingleOutputStreamOperator<JSONObject> etlStream) {
        return etlStream.map(new MapFunction<JSONObject, DwsUserRegisterBean>() {
            @Override
            public DwsUserRegisterBean map(JSONObject jsonObject) throws Exception {
                DwsUserRegisterBean dwsUserRegisterBean = JSONObject.parseObject(jsonObject.toString(), DwsUserRegisterBean.class);
                return dwsUserRegisterBean;
            }
        });
    }

    private static SingleOutputStreamOperator<JSONObject> getEtlStream(DataStreamSource<String> dataStreamSource) {
        return dataStreamSource.flatMap(new RichFlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                try {
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    String create_time = jsonObject.getString("create_time");
                    if (create_time != null) {
                        collector.collect(jsonObject);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
